package com.JFrameView;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import java.awt.*;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Arrays;
import java.util.Date;

/**
 * author:hlc
 * date:2023/9/24
 *
 * @author 17930
 */
public class Window implements Runnable {
   Object[][] tableData = new Object[40][3];
   String path_url = "";
   static int count = 0;
   /**
    * TODO(二维数据的扩容)
    *
    * @param url
    * @param time
    * @param code
    */
   //定义一维数据作为列标题
   Object[] columnTitle = {"服务器名称", "响应时间", "状态码"};
   JTable table = new JTable(tableData, columnTitle);

   public synchronized void init() throws FontFormatException {
      JFrame frame = new JFrame();
      ImageIcon icon = new ImageIcon("images/icon.png");
      frame.setIconImage(icon.getImage());
      WindowController windowController = new WindowController(frame);
      frame.setSize(1000, 600);
      //frame.setUndecorated(true);//去掉装饰
      frame.setBackground(Color.white);
      //frame.getContentPane().setBackground(Color.gray);
      frame.setResizable(true);
      frame.setLocationRelativeTo(null);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLayout(null);//空布局
      frame.addMouseListener(windowController);
      frame.addMouseMotionListener(windowController);


      JTextField textField = new JTextField();
      JButton button = new JButton("请输入文件路径进行检测");

      textField.setBounds(650, 100, 300, 300);
      textField.setColumns(20);
      button.setBounds(0, 100, 80, 300);

      JPanel panel = new JPanel();

      panel.setBounds(500, 50, 300, 300);
      panel.add(textField);
      //panel.add(button);

      JPanel panel1 = new JPanel();
      panel.setBounds(650, 50, 300, 300);
      // panel.add(textField);
      panel.add(button);

      button.addActionListener(e -> {
         path_url = textField.getText();
      });

      JPanel top = new JPanel();
      top.setLayout(null);
      top.setBounds(1, 0, 599, 50);
      top.setBackground(Color.BLUE);
      JLabel label = new JLabel();
      label.setBounds(190, 10, 220, 20);
      label.setBackground(Color.white);
      label.setText("自动化服务器状态监测");
      label.setFont(new Font("微软雅黑", Font.TRUETYPE_FONT, 20));
      label.setForeground(Color.white);
      top.add(label);
      JPanel tableFrame = new JPanel();
      tableFrame.setBounds(1, 60, 598, 500);
      tableFrame.setBackground(Color.white);
      //以二维数组和一维数组来创建一个JTable对象
      /*table = new JTable(tableData, columnTitle);*/
      JTableHeader tab_header = table.getTableHeader();               //获取表头
      tab_header.setFont(new Font("微软雅黑", Font.PLAIN, 15));
      tab_header.setPreferredSize(new Dimension(tab_header.getWidth(), 30));   //修改表头的高度
      table.setFont(new Font("微软雅黑", Font.PLAIN, 13));
      table.setRowHeight(30);
      table.setShowGrid(false);
      //将JTable对象放在JScrollPane中，并将该JScrollPane放在窗口中显示出来
      table.setBackground(Color.white);
      table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
         @Override
         public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
            Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            c.setBackground(row % 2 == 0 ? Color.LIGHT_GRAY : Color.WHITE);
            return c;
         }
      });
      table.setRowHeight(30);
      table.setFont(new Font("微软雅黑", Font.TRUETYPE_FONT, 15));
      tableFrame.add(new JScrollPane(table));
      frame.add(top);
      frame.add(tableFrame);
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      frame.add(panel);
      frame.add(panel1);
      frame.setVisible(true);
   }

   private static Object[] request(URL url) {
      HttpClient httpClient = HttpClient.newHttpClient();
      HttpRequest request = null;
      HttpResponse<String> httpResponse = null;
      try {
         request = HttpRequest.newBuilder(url.toURI()).GET().timeout(Duration.ofSeconds(10)).build();
         httpResponse = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
      } catch (IOException e) {
         System.out.println("请求失败");
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         Date date = new Date();
         String dateFormat = sdf.format(date);
         return new Object[]{url, dateFormat, 404};
         //e.printStackTrace();
      } catch (InterruptedException e) {
         e.printStackTrace();
      } catch (URISyntaxException e) {
         throw new RuntimeException(e);
      }
      // System.out.println(httpResponse);
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      Date date = new Date();
      String dateFormat = sdf.format(date);

      System.out.println("====");
      /*window.addTableDate(httpResponse.uri().toString(), dateFormat, httpResponse.statusCode());*/
      return new Object[]{url, dateFormat, httpResponse.statusCode()};
   }

   @Override
   public void run() {
      URL url = null;
      try {
         BufferedReader re;
         if (path_url.equals("")) {
            re = new BufferedReader(new FileReader("resources\\demo.txt"));
         } else {
            re = new BufferedReader(new FileReader(path_url));
         }
         //BufferedReader re = new BufferedReader(new FileReader("resources\\demo.txt"));
         String s;
         while ((s = re.readLine()) != null) {
            url = new URL(s);
            if (count > tableData.length - 1) {
               Object[][] objects = Arrays.copyOf(tableData, count * 2);
               tableData = objects;
               System.out.println("触发扩容");
            }
            tableData[count++] = request(url);
         }
      } catch (FileNotFoundException e) {
         throw new RuntimeException(e);
      } catch (IOException e) {
         throw new RuntimeException(e);
      }
      table.repaint();
   }

   public void writeExcel() {
   }
}

